package com.shop.servlet;

import com.shop.model.Course;
import com.shop.service.CourseService;
import com.shop.service.ICourseService;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.List;

@WebServlet("/search")
public class CourseServlet extends HttpServlet {
    ICourseService icourseService = new CourseService();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=UTF-8");
        req.setCharacterEncoding("UTF-8");

        List<Course> course = null;
        String studentId = req.getParameter("studentId");
        if(req.getParameter("query").matches("^[1-9]\\d*$")){
            int query = Integer.parseInt(req.getParameter("query"));
            System.out.println("CourseServlet:24:"+query);
            course = icourseService.searchCourse(query,null);
        }else{
            String query = req.getParameter("query");
            System.out.println("CourseServlet:28:"+query);
            course = icourseService.searchCourse(-1,query);
        }

            if(course != null){
                req.setAttribute("course",course);
                req.setAttribute("studentId",studentId);
                req.getRequestDispatcher("search_course.jsp").forward(req,resp);
            }else{
                req.setAttribute("error","课程不存在");
                req.getRequestDispatcher("course.jsp").forward(req,resp);
            }

    }
}
